package com.wxm.killing.mq.common.auth;

import com.wxm.killing.mq.common.enums.HttpStatusEnum;
import com.wxm.killing.mq.common.exception.BaseException;
import com.wxm.killing.mq.common.model.JsonResult;
import com.wxm.killing.mq.common.redis.RedisUtil;
import com.wxm.killing.mq.common.util.CommonUtil;
import com.wxm.killing.mq.common.util.JsonUtil;
import com.wxm.killing.mq.dao.TbUserDao;
import com.wxm.killing.mq.entity.RequestInfo;
import com.wxm.killing.mq.entity.TbUser;
import com.wxm.killing.mq.service.CommonCacheService;
import com.wxm.killing.mq.startup.StartupLoading;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class LoninFilter implements Filter {

    @Autowired
    private TbUserDao tbUserDao;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private CommonCacheService commonCacheService;

    final static Logger logger = LoggerFactory.getLogger(LoninFilter.class);

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) req;
            //获取请求连接
            String spath = request.getServletPath();
            logger.info("请求连接spath:" + spath);
            //如果不需要拦截
            if (spath.contains("druid")) {
                chain.doFilter(req, res);
                return;
            }
            //从请求head里取出token
            String token = request.getParameter("token");
            if (StringUtils.isEmpty(token)) {
                logger.info("没有token参数");
                throw new BaseException(0, HttpStatusEnum.UNAUTHORIZED.getMsg());
            }

            //请求频率限制
            RequestInfo requestInfo = new RequestInfo();
            requestInfo.setUrl(spath);
            requestInfo.setToken(token);
            String md5 = DigestUtils.md5DigestAsHex(JsonUtil.Java2Json(requestInfo).getBytes());
            if (redisUtil.hasKey(md5)) {
                logger.info("请求频率过快，请稍后再试");
                throw new BaseException(0, "请求频率过快，请稍后再试");
            }
            redisUtil.set(md5, "run slow", 2);

            TbUser tbUser = commonCacheService.getUserByToken(token);

            //判断用户是否登录
            if (tbUser == null) {
                throw new BaseException(0, HttpStatusEnum.UNAUTHORIZED.getMsg());
            }

            if ("1".equals(tbUser.getIsFrozen())) {
                logger.info("该帐号已被冻结，请联系管理员");
                throw new BaseException(0, "该帐号已被冻结，请联系管理员");
            }

            if ("1".equals(tbUser.getIsLock())) {
                logger.info("该帐号已被封号，请联系管理员");
                throw new BaseException(0, "该帐号已被封号，请联系管理员");
            }
            //用户信息存放到本地线程
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(tbUser.getUserId());
            UserInfoContext.setUserInfo(userInfo);
            chain.doFilter(req, res);
        } catch (BaseException e) {
            res.setContentType("text/html;charset=UTF-8");
            PrintWriter out = res.getWriter();
            JsonResult jsonResult = new JsonResult();
            jsonResult.setStatus(e.getErrStatus());
            jsonResult.setMsg(e.getErrMsg());
            out.append(JsonUtil.Java2Json(jsonResult));
            return;
        } finally {
            BaseContextHandler.remove();
        }

    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }


}
